import Log from '../../sql/module/log';
import fetch from 'node-fetch';
import { Success, HttpException, Fail, NotFound } from '../../code/http-exception';
import { ListValidator, InfoValidator } from '../../validators/public';
import auth from '../../middlewares/auth';
import { Op } from "sequelize";
import { config } from '../../config';

const router: Api = new Map()

//@query limit number 每页数据量 1-99 *
//@query page_index number 页数 *
//@body name string 操作人昵称
//@body type string 操作类型 create delete updata
router.set('/loglist', [auth('recordList'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const name = v.get('body.name')
    const type = v.get('body.type')
    const createdAt = v.get('body.search_time')
    const search_key: any = {}
    type && (search_key.type = type)
    name && (search_key.name = {
        [Op.substring]: name
    })
    const addDay = (date: Date, day: number) => {
        const newDate = new Date(date);
        newDate.setDate(newDate.getDate() + day);
        return newDate;
    }
    createdAt && (search_key.createdAt = {
        [Op.and]: [{
            [Op.gte]: createdAt[0] ? new Date(createdAt[0]) : new Date(0)
        },
        {
            [Op.lte]: createdAt[1] ? addDay(new Date(createdAt[1]), 1) : addDay(new Date(), 1)
        }]
    })

    const { count, rows } = await Log.findAndCountAll({
        attributes: ['id', 'name', 'type', 'msg', 'path', 'hasReset', 'createdAt'],
        where: search_key,
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        order: [['id', 'DESC']]
    })
    throw new Success({ list: rows, total: count }, 20000)
}])
//@query id number 记录id *
router.set('/logInfo', [auth('recordDetail'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')

    const log = await Log.findOne({
        where: {
            id
        }
    })
    if (!log) throw new NotFound()
    throw new Success(log, 20000)
}])
//@query id number 记录id *
router.set('/delete', [auth('deleteRecord'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')

    await Log.destroy({
        where: {
            id
        }
    })
    throw new Success('删除成功', 20000)
}])
//@query id number 记录id *
router.set('/reset', [auth('resetRecord'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const log = await Log.findOne({
        where: {
            id
        }
    })
    if (!log) { throw new NotFound() }
    const { hasReset, path, _id, dff } = log.dataValues
    if (hasReset) throw new Fail()
    const url = config.BASEURL + path + '?id=' + _id
    const res = await fetch(url, {
        method: 'POST',
        body: JSON.stringify({ dff }),
        headers: {
            Authorization: 'Bearer ' + ctx.auth.token,
            'Content-Type': 'application/json',
            accept: 'application/json'
        } as any
    })
    if (res.status !== 200) {
        throw new Fail('恢复失败')
    }
    const data: any = await res.json()
    if (data.errorCode === 20000) {
        await Log.update({
            hasReset: 1
        }, {
            where: { id }
        })
        throw new Success('恢复成功')
    } else if (data.errorCode === 20001) {
        await Log.update({
            hasReset: 1
        }, {
            where: { id }
        })
        throw new Fail(data.msg)
    }
    throw new HttpException()
}])

export { router }